const net = require("node:net");
// 导入ws模块
const WebSocket = require("ws");

const { onSetRfidData } = require('./utils/mock-rfid-behavior.cjs')

// 心跳时长
const heartbeatInterval = 800;

const connectTcp = (config) => {
  const client = new net.Socket();

  const onContentClient = () => {
    client.connect(config.port, config.host, () => {
      console.log("connected");
      // 开始发送心跳
      setInterval(() => {
        const data = `D90401002002`;
        // 16进制的data 转成二进制发送
        client.write(Buffer.from(data, "hex"), () => {
          // console.log("head");
          // console.log('Sent data:', data);
        });
      }, heartbeatInterval);
    });
  };

  client.on("data", (data) => {
    // 接收到的数据
    parseClientBufferData(data);
  });

  client.on("end", () => {
    console.log("Connection closed.");
    retryContent();
  });

  client.on("error", (err) => {
    console.error("Error occurred:", err);
    client.destroy(); // 销毁客户端
    retryContent();
  });
  function retryContent() {
    setTimeout(onContentClient, 1000);
  }

  onContentClient();

  function parseClientBufferData(bytes) {
    // const bytes = data.map(byte => parseInt(byte, 16));

    // 提取包头
    const header = bytes[0];

    // 检查包头和len
    if (header !== 0xd9) {
      return false;
    }

    // 检查指令码是否为盘存 EPC 数据指令码 20
    if (bytes[4] !== 0x20) {
      return false;
    }

    // 提取 len
    const len = bytes[1];

    const antennaNumber = bytes[7];
    const epcData = bytes.subarray(10, len - 3);
    const rfid = epcData.toString("hex").toUpperCase();
    // 调用函数进行值的设置，设置 ip，天线号，EPC 数据

    // const key = ``; // 设置key固定的格式
    // const key = `${config.host}:${config.port}-${antennaNumber}`;
    const key = `${config.host}-${antennaNumber}`;
    const sendResult = {
      key,
      ip: config.host,
      port: config.port,
      antenna: antennaNumber,
      rfid,
    };

    if (antennaNumber === 0) return

    // rfid长度大于 20,否则判定为无效
    // if (rfid.length > 20) {
    // 防错工装,判断仅仅传递有效
    // 判断 天线,只取数组中的
    // console.log(`${new Date().toLocaleString()} ---${sendResult.key}===${sendResult.rfid}`);

    // 在这里模拟处理相关的执行逻辑，计算进入离开
    onSetRfidData(sendResult)

    const antennas = [1, 2, 4, 7];
    if (antennas.includes(antennaNumber)) {
      broadcast(JSON.stringify(sendResult));
    }
    // }
  }
};

connectTcp({
  host: "192.168.100.188",
  port: 4001,
});

// 创建一个WebSocket服务器，绑定到 port 端口
const wss = new WebSocket.Server({ noServer: true });

// 当有客户端连接时触发
wss.on("connection", (ws) => {
  // 接收客户端发来的消息
  ws.on("message", (message) => {
    // 如果 message 开头为 ping 终止
    if (message == "ping") return;
  });

  // 当连接关闭时触发
  ws.on("close", () => {
    console.log("客户端已断开连接");
  });
});

// 发送消息
function broadcast(message) {
  wss.clients.forEach((client) => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(message);
    }
  });
}

// 添加一个监听器以优雅地处理程序退出，清除定时器
process.on("SIGINT", function () {
  console.log("\nGracefully shutting down from SIGINT (Ctrl-C)");
  process.exit();
});

module.exports = wss;
